package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 给店铺种类添加缓存
     *
     * @return
     */
    @Override
    public Result queryTypes() {
        String KEY = CACHE_SHOP_TYPE_KEY;
        //1.在redis中查找店铺种类信息
//       String shopTypeJSON = stringRedisTemplate.opsForList().rightPop(KEY);

        List<String> shopTypeJSON = stringRedisTemplate.opsForList().range(KEY, 0, 9);
        String[] arr = shopTypeJSON.toArray(new String[shopTypeJSON.size()]);
        ArrayList<ShopType> list = new ArrayList<>();
        //2.命中：返回店铺种类信息
        if (shopTypeJSON.size() > 0) {
            for (int i = 0; i < shopTypeJSON.size(); i++) {
                ShopType shopType = JSONUtil.toBean(arr[i], ShopType.class, false);
                list.add(shopType);
            }
            return Result.ok(list);
        }
        //3.未命中：到数据库中查找店铺种类信息
        List<ShopType> shopType = list();
//        ShopType shopType = getById(id);
        //4.判断查询结果是否为空
        if (shopType == null) {
            //5.结果为空：报错
            Result.fail("亲~没有这个店铺种类");
        }
        Object[] array = shopType.toArray();
        //6.有查询结果：将数据保存到redis中
        for (int i = 0; i < shopType.size(); i++) {
            String jsonStr = JSONUtil.toJsonStr(array[i]);
            stringRedisTemplate.opsForList().rightPush(KEY, jsonStr);
        }
        //7.返回店铺种类信息
        return Result.ok(shopType);
    }
}
